<template>
	<div>
		<div style="position: fixed;z-index: 10;flex-direction: column;background: white;width: 100%;margin-top: -10px"><h1
				class="header-text">
			学生信息管理
		</h1>
			<div class="search-bar">
				<el-input placeholder="输入学号/姓名   搜索学生" v-model="searchQuery" @input="handleInput">
				</el-input>
			</div>
			<div style="float:left;">
				<el-button type="primary" @click="handleAdd">新增用户
					<el-icon style="margin-left: 10px;">
						<CirclePlusFilled/>
					</el-icon>
				</el-button>
				<el-button type="danger" @click="handleBatchDelete" :disabled="!multipleSelection.length">批量删除
					<el-icon style="margin-left: 10px;">
						<RemoveFilled/>
					</el-icon>
				</el-button>
			</div>
			<div style="float: right;margin-right: 100px">
			<el-pagination @size-change="handleSizeChange"
										 @current-change="handleCurrentChange"
										 :current-page="currentPage"
										 :page-sizes="[10, 20, 50,100]"
										 :page-size="pageSize"
										 layout="total, sizes, prev, pager, next, jumper"
										 :total="totalCount"
			/></div>
		</div>
		<div class="table-container">
			<el-table
					:data="paginatedStudents"
					style="width: 100%;top:160px;"
					@selection-change="handleSelectionChange"
					@row-click="handleRowClick"
			>
				<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column prop="sid" label="学号" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.sid)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="sname" label="姓名" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.sname)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="gender" label="性别" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.gender)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="spassword" label="密码" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.spassword)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="dept" label="部门" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.dept)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="sclass" label="班级" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.sclass)"></span>
					</template>
				</el-table-column>
				<el-table-column prop="sphone" label="手机号" style="width: 12.5%">
					<template #default="scope">
						<span v-html="highlightMatch(scope.row.sphone)"></span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="100">
					<template #default="scope">
						<el-button type="danger" size="small" @click.stop="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<!-- 模态框（对话框） -->
		<el-dialog :model-value="dialogVisible" title="学生信息" @close="dialogVisible = false">
			<el-form :model="selectedStudent">
				<el-form-item label="学号">
					<el-input
							:disabled="isEdit"
							v-model="selectedStudent.sid"
							autocomplete="off"
							:class="{'is-error': sidExistError}"
							@input="checkSid"
					></el-input>
					<span class="error-message" v-if="sidExistError">该学号已使用，请重新输入！</span>
				</el-form-item>
				<el-form-item label="姓名">
					<el-input v-model="selectedStudent.sname" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="selectedStudent.gender">
						<el-radio label="男">男</el-radio>
						<el-radio label="女">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="密码">
					<el-input v-model="selectedStudent.spassword" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门">
					<el-input v-model="selectedStudent.dept" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="班级">
					<el-input v-model="selectedStudent.sclass" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="电话">
					<el-input v-model="selectedStudent.sphone" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="问题">
					<el-input v-model="selectedStudent.problem" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="答案">
					<el-input v-model="selectedStudent.text" autocomplete="off"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleConfirm" v-if="!showButton">确认修改</el-button>
				<el-button type="primary" @click="addConfirm" v-if="showButton">确认添加</el-button>
			</template>
		</el-dialog>
	</div>
	<br class="fixed-container highlight">
</template>
<script>
import AxiosService from '@/plugins/Axios.js';
import {ElMessage} from "element-plus";
import {CirclePlusFilled, RemoveFilled} from "@element-plus/icons-vue";

export default {
	components: {
		RemoveFilled,
		CirclePlusFilled
	},
	data() {
		return {
			searchQuery: '',
			paginatedStudents: [],
			students: [], // 存储所有学生数据
			studentSID: [], // 存储学号数组
			showButton: false,
			dialogVisible: false,
			selectedStudent: {
				sid: '',
				sname: '',
				gender: '',
				spassword: '',
				dept: '',
				sclass: '',
				sphone: '',
				problem: '',
				text: ''
			},
			multipleSelection: [], // 存储选中的多行数据
			sidExistError: false, // 学号已存在错误状态
			isEdit: false, // 是否处于编辑模式
			originalSid: '', // 原始学号，用于编辑时检查是否修改了学号
			currentPage: 1, // 当前页码
			pageSize: 10, // 每页显示条数
			totalCount: 0, // 总条数
			size: 'large', // 分页组件大小
			background: false, // 是否有背景色
			disabled: false // 是否禁用
		};
	},
	computed: {
		paginatedStudents() {
			const start = (this.currentPage - 1) * this.pageSize;
			const end = start + this.pageSize;
			return this.paginatedStudents.slice(start, end);
		}
	},
	methods: {
		handleInput() {
			const results = this.students.filter(student => {
				const searchString = `${student.sname} ${student.sid} ${student.sclass}`;
				return searchString.includes(this.searchQuery);
			});
			results.sort((a, b) => {
				const aMatchLength = this.calculateMatchLength(a);
				const bMatchLength = this.calculateMatchLength(b);
				return bMatchLength - aMatchLength;
			});
			this.paginatedStudents = results;
		},
		calculateMatchLength(student) {
			const searchString = `${student.sname} ${student.sid} ${student.sclass}`;
			const matchIndex = searchString.indexOf(this.searchQuery);
			if (matchIndex !== -1) {
				return this.searchQuery.length;
			}
			return 0;
		},
		highlightMatch(text) {
			if (!this.searchQuery) return text;
			const regex = new RegExp(this.escapeRegExp(this.searchQuery), 'gi');
			return text.replace(regex, match => `<span style="color: #ff00f3;font-weight: bolder">${match}</span>`);
		},
		escapeRegExp(string) {
			return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
		},
		async handleDelete(index, row) {
			try {
				await AxiosService.deleteStudent(row.sid);
				this.students.splice(index, 1);
				this.totalCount--; // 更新总条数
				this.$message({
					type: 'success',
					message: '学生信息删除成功!'
				});
				await this.fetchStudents();
			} catch (error) {
				console.error('Error deleting student:', error);
				this.$message({
					type: 'error',
					message: '删除学生信息失败，请重试!'
				});
			}
		},
		async handleBatchDelete() {
			try {
				const deletePromises = this.multipleSelection.map(student => AxiosService.deleteStudent(student.sid));
				await Promise.all(deletePromises);
				this.students = this.students.filter(student => !this.multipleSelection.includes(student));
				this.totalCount -= this.multipleSelection.length; // 更新总条数
				this.multipleSelection = []; // 清空选中
				this.$message({
					type: 'success',
					message: '批量删除成功!'
				});
				await this.fetchStudents()
			} catch (error) {
				console.error('Error batch deleting students:', error);
				this.$message({
					type: 'error',
					message: '批量删除失败，请重试!'
				});
			}
		},
		handleAdd() {
			this.showButton = true;
			this.isEdit = false;
			this.sidExistError = false;
			this.selectedStudent = {
				sid: '',
				sname: '',
				gender: '',
				spassword: '',
				dept: '',
				sclass: '',
				sphone: '',
				problem: '',
				text: ''
			};

			this.dialogVisible = true;
		},
		handleRowClick(row) {
			this.isEdit = true;
			this.originalSid = row.sid;
			this.selectedStudent = {...row};
			this.dialogVisible = true;
		},
		async handleConfirm() {
			try {
				// 直接操作 this.selectedStudent 对象
				if (this.selectedStudent.sclass.includes('班')) {
					this.selectedStudent.sclass = this.selectedStudent.sclass.replace('班', '');
				}
				// 更新学生信息
				await AxiosService.updateStudent(this.selectedStudent);
				// 显示成功的消息
				this.$message({
					type: 'success',
					message: '学生信息更新成功!'
				});
				// 关闭对话框
				this.dialogVisible = false;
				// 重新获取学生列表
				await this.fetchStudents();
				this.handleInput()
			} catch (error) {
				// 显示错误的消息
				this.$message({
					type: 'error',
					message: '操作失败，请重试!'
				});
			}
		},
		async addConfirm() {
			if (this.selectedStudent.sid === '') {
				ElMessage.error("请输入学号！")
			} else {
				this.showButton = false;
				try {
					if (this.selectedStudent.sclass.includes('班')) {
						this.selectedStudent.sclass = this.selectedStudent.sclass.replace('班', '');
					}
					await AxiosService.addStudent(this.selectedStudent);
					this.$message({
						type: 'success',
						message: '学生信息添加成功!'
					});
					this.dialogVisible = false;
					await this.fetchStudents();
				} catch (error) {
					this.$message({
						type: 'error',
						message: '操作失败，请重试!'
					});
				}
			}
		},
		async fetchStudents() {
			try {
				// 获取所有学生数据
				const data = await AxiosService.fetchStudents();
				this.students = data;
				this.totalCount = data.length; // 更新总条数,
				this.students = data.map(student => ({
					...student,
					sclass: student.sclass + '班'
				}));
				this.paginatedStudents = [...this.students];
				this.studentSID = this.students.map(student => student.sid);
			} catch (error) {
				console.error('Error fetching students:', error);
			}
		},
		handleSizeChange(size) {
			this.pageSize = size;
			this.currentPage = 1; // 每次改变每页条数时，重置为第一页
		},
		handleCurrentChange(page) {
			this.currentPage = page;
		},
		async checkSid() {
			// 检查学号是否已存在
			this.sidExistError = this.studentSID.includes(this.selectedStudent.sid) && this.originalSid !== this.selectedStudent.sid;
		},
		handleSelectionChange(val) {
			this.multipleSelection = val;
		}
	},
	
	async created() {
		await this.fetchStudents();
	}
};

</script>

<style scoped>

.fixed-container {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	background-color: #fff;
	z-index: 999;
	padding: 10px;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.error-message {
	color: red;
	font-size: 12px;
}

.highlight {
	color: red;
}

.search-bar {
	width: 95%;
	margin-bottom: 20px;
}

.header-text {
	background-clip: padding-box;
	display: flex;
	flex-direction: column;
	float: left;
	background: -webkit-linear-gradient(315deg, #3f9dfd 15%, #f36b6b);
	-webkit-background-clip: text;
	-webkit-text-fill-color: transparent;
	color: transparent;
	font-weight: bolder;
}
</style>
